package commands;

import expression.*;
import exceptions.ParseException;
import memory.Memory;

public class AssignCommand extends Command {

	Memory memory;
	String variableName;
	Expression expression;
	Command next;

	@Override
	public void run() {
		memory.assign(variableName, expression.calculate());
	}

	@Override
	public Command getNext() {
		return next;
	}

	public AssignCommand(String command, Memory memory, int lineNumber)
			throws ParseException {
		super(lineNumber);
		this.memory = memory;
		command = fixString(command);
		int posOfAssign = command.indexOf("=");
		if (posOfAssign == -1) {
			throw new ParseException("There is no = at assign statement");
		}
		if (posOfAssign == 0) {
			throw new ParseException(
					"There is no variable name at assign statement");
		}
		if (posOfAssign == command.length()) {
			throw new ParseException("There is expression at assign statement");
		}

		variableName = command.substring(0, posOfAssign);
		if (!Memory.isCorrectVariableName(variableName)) {
			throw new ParseException(variableName
					+ " is not valid name of variable");
		}

		expression = new Sum(command.substring(posOfAssign + 1), memory);
	}

	@Override
	public void setNext(Command command) {
		next = command;
	}
}
